<template>
  <div class="img-search-container">
    <el-upload
      class="upload-demo"
      ref="uploadImg"
      :show-file-list="false"
      drag
      :auto-upload="false"
      :on-change="
        (file, fileList) => {
          handleAvatarChangeIcon(file, fileList, 'img');
        }
      "
    >
      <div v-if="!imgUrl" v-loading="loading" style="display: flex; justify-content: center; align-items: center">
        <div class="el-upload__text"><em style="line-height: 24px">点击上传</em> / 拖拽到此区域</div>
      </div>
      <div v-else v-loading="loading">
        <img :src="imgUrl" alt="" />
      </div>
    </el-upload>

    <div class="mt20" style="display: flex; justify-content: space-between; align-items: center">
      <el-input disabled v-model="imgUrl" placeholder="图片链接"></el-input>
      <el-button class="yyx-btn ml16" type="primary" :disabled="!(imgUrl && imgId) || loading" @click="imgSearchSubmit"
        >搜索</el-button
      >
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import useMultipartOssStore from "@/store/modules/multipartOssStore.js";
const ossStore = useMultipartOssStore();
import { ElMessage } from "element-plus";
import { _debounce } from "@/utils/index"; //防抖，多次频繁触发时，只执行最后一次
import { CloseBold, Loading } from "@element-plus/icons-vue";
import { getFolder } from "@/utils/index";
import { useRouter } from "vue-router";
const router = useRouter();

const emit = defineEmits(["submit", "close"]);
const loading = ref(false);
const imgUrl = ref("");
const imgId = ref("");

const imgSearchSubmit = () => {
  emit("submit", { imgUrl: imgUrl.value, imgId: imgId.value });
};

//====================================图片上传========================================================================================
import { imgsUpload } from "@/api/products/specifications";

const FileList = ref([]);
const handleAvatarChangeIcon = _debounce(async (file, fileList, type = "img") => {
  //选中文件触发的change事件
  console.log("触发文件上传===", file);
  FileList.value = fileList;
  loading.value = true;

  const flag = fileType(type, [file], type);
  if (flag) {
    await customUpload(file, { file: file }, type);
    loading.value = false;
  } else {
    ElMessage({
      message: "只能上传图片文件",
      type: "error",
      offset: 60
    });
    loading.value = false;
  }
}, 100);

/**
 * 上传
 */
const customUpload = async (item, option, type) => {
  // 合并已上传和当前上传文件
  const folder = getFolder();
  const objName = folder + option.file.name;
  await ossStore
    .submit(objName, option.file.raw)
    .then(async res => {
      await ossStore.setACL(objName, fileReadRole.publicRead);
      res.fileUrl = await ossStore.signatureUrl(objName);
      console.log("图片上传成功，地址为===", res.fileUrl.split("?")[0]);
      item["img"] = res.fileUrl.split("?")[0];
      item["folder"] = objName;
      imgUrl.value = res.fileUrl.split("?")[0];
      imgId.value = option.file.uid;

      const Option = JSON.parse(JSON.stringify(option));
      uploadIMG(Option); //图片上传到业务端
    })
    .catch(err => {
      alert(JSON.stringify(err));
    });
};
//将图片上传到业务端服务
const uploadIMG = option => {
  const nameArr = option.file.name.split(".");
  const uploadArr = [
    {
      fileId: option.file.uid,
      objectName: "/dbo-mall" + option.file.folder, //目录＋文件名称
      url: option.file.url || option.file.video,
      access: "public-read",
      fileName: option.file.name, //文件名称
      bucketName: "51-jzt-dev",
      size: option.file.size,
      type: true,
      suffix: nameArr[nameArr.length - 1]
    }
  ];
  imgsUpload(uploadArr).then(res => {
    console.log(909090, res);
  });
};
/**
 * 校验文件类型
 */
const fileType = (type, fileList) => {
  let flag = true;
  if (type === "img") {
    for (let item of fileList) {
      if (!(item.raw.type === "image/jpeg" || item.raw.type === "image/png")) {
        flag = false;
      }
    }
  } else if (type === "video") {
    for (let item of fileList) {
      if (!(item.raw.type === "video/mp4")) {
        flag = false;
      }
    }
  }
  return flag;
};
const fileReadRole = {
  defaultRole: "",
  privateRole: "private",
  publicRead: "public-read",
  publicReadWrite: "public-read-write"
};
</script>

<style lang="scss" scoped>
:deep(.el-upload-dragger) {
  padding: 0 !important;
  height: 144px;
  display: flex;
  align-items: center;
  justify-content: center;

  img {
    width: 100%;
    object-fit: cover;
  }
}

.img-search-container {
  position: absolute;
  top: 40px;
  left: 0;
  right: 0;
  padding: 10px 20px;
  background-color: white;
  box-shadow: 0px 5px 12px 0px rgba(4, 19, 74, 0.16);
  border-radius: 8px;
  z-index: 3;
}
</style>
